﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using DataDAL;

namespace WinTrainGuoHeng
{
    public partial class Form1 : Form
    {
        //检测文件改动
        Timer timer = null;
        //路径设置用
        Timer timer2 = null;
        //活动文件路径
        string changeFilePath = string.Empty;
        //文件大小
        long fileSize = 0;

        public Form1()
        {
            InitializeComponent();
        }
        private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
        {
            if (timer != null)
            {
                timer.Stop();
                timer.Dispose();
            }
            timer = new Timer();
            timer.Enabled = false;

            AddTextMsg("有改动了");
            changeFilePath = e.FullPath;
            LogManager.AddLog("监视路径：" + e.FullPath, "Log");
            //获取文件大小
            FileInfo file = new FileInfo(changeFilePath);
            fileSize = file.Length;
            AddTextMsg("文件大小=" + fileSize);

            timer.Tick += timer_Tick;
            timer.Interval = 7 * 1000;//秒
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            FileInfo file = new FileInfo(changeFilePath);
            long fileSize2 = file.Length;
            if (fileSize2 == fileSize)
            {
                //说明文件没有改变大小了
                AddTextMsg("文件没有改变大小了,大小为=" + fileSize2);
                LogManager.AddLog("文件没有改变大小了,大小为=" + fileSize2, "Log");
                List<CoalByTrain> list = new List<CoalByTrain>();
                try
                {
                    //获取该文件的文本 
                    FileStream stream = file.OpenRead();
                    StreamReader reader = new StreamReader(stream, Encoding.Default);
                    int rowIndex = 1;
                    while (true)
                    {
                        int peek = reader.Peek();
                        if (peek > 0)
                        {
                            string lineTxt = reader.ReadLine();
                            if (rowIndex >= 6)
                            {
                                //封装数据
                                //LogManager.AddLog(lineTxt, "Log");
                                string[] dataArr = lineTxt.Split(',');
                                CoalByTrain model = new CoalByTrain();
                                string ghtime = dataArr[1].Trim();
                                //年月日
                                string yyyymmdd = ghtime.Split('_')[0];
                                yyyymmdd = yyyymmdd.Insert(4, "-").Insert(7, "-");
                                string time = ghtime.Split('_')[1];
                                time = time.Insert(2, ":").Insert(5, ":");
                                model.GuoHengTime = yyyymmdd + " " + time;

                                model.SeqNo = Convert.ToInt16(dataArr[0].Trim());
                                model.TrainNo = dataArr[3].Trim();
                                model.TrainType = dataArr[4].Trim();
                                model.GrossWeight = float.Parse(dataArr[5]);
                                model.Tare = float.Parse(dataArr[6]);
                                model.NetWeight = float.Parse(dataArr[7]);
                                model.BiaoWeight = float.Parse(dataArr[8]);
                                model.YingKui = float.Parse(dataArr[9]);
                                model.Speed = float.Parse(dataArr[10]);
                                list.Add(model);
                            }
                            rowIndex++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    reader.Close();
                    reader.Dispose();
                    stream.Close();
                    stream.Dispose();
                }
                catch (Exception)
                {
                    AddTextMsg("该文本数据格式有误");
                    LogManager.AddLog("该文本数据格式有误", "Log");
                }
                //保存数据           
                TrainDAL dal = new TrainDAL();
                //数据json格式               
                int count = dal.AddList(list);
                if (count > 0)
                {
                    AddTextMsg("成功添加过衡数据条数=" + count);
                    LogManager.AddLog("成功添加过衡数据条数=" + count, "Log");
                }
                else
                {
                    AddTextMsg("添加失败");
                }
                LogManager.AddLine("Log", 1);
            }
            timer.Stop();
            timer.Dispose();
        }

        public void AddTextMsg(string msg)
        {
            List<string> list = this.textBox1.Lines.ToList();
            list.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + msg);
            this.textBox1.Lines = list.ToArray();
            this.textBox1.Select(this.textBox1.TextLength, 0);//光标定位到文本最后
            this.textBox1.ScrollToCaret();//滚动到光标处
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                string monitorFilePath = System.Configuration.ConfigurationManager.AppSettings["MonitorFilePath"];
                this.fileSystemWatcher1.Path = monitorFilePath;//监测路径
                this.fileSystemWatcher1.EnableRaisingEvents = true;
                if (this.fileSystemWatcher1.EnableRaisingEvents)
                {
                    AddTextMsg("监测已启动...");
                    LogManager.AddLog("监测已启动...", "Log");
                }
                //隐藏任务栏窗体
                this.ShowInTaskbar = false;
            }
            catch (Exception ex)
            {
                LogManager.AddLog("异常，" + ex.Message, "Log");
            }
        }


        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this.WindowState = FormWindowState.Minimized;
            this.Visible = false;
            e.Cancel = true;
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
        }




    }
}
